package com.bw.Controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.client.Myclient;
import com.bw.common.BResult;
import com.bw.domain.House;
import com.bw.domain.User;
import com.bw.service.HouseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
public class ListController {
    @Autowired
    HouseService houseService;
    @Autowired
    Myclient myclient;
    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("list")
    public BResult list(Integer pageNum, Integer size,HttpServletRequest request){
        User token = myclient.SelectByToken(request.getHeader("token"));
        if (token==null){
            return  BResult.error("token为空");
        }

        PageHelper.startPage(pageNum,size);
        List<House> list = houseService.list();
        PageInfo<House> info = new PageInfo<>(list);
           redisTemplate.opsForValue().set("hlist:"+pageNum,info);
        return  BResult.success(info);
    }
    @RequestMapping("add")
    public BResult add(@RequestBody House house, HttpServletRequest request){
        User token = myclient.SelectByToken(request.getHeader("token"));
        if (token==null){
            return  BResult.error("token为空");
        }
        LambdaQueryWrapper<House> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(House::getPname,house.getPname());
        House one = houseService.getOne(wrapper);
        if (one!=null){
            return  BResult.error("名字已重复");
        }
        //7. 在创建租赁订单时，后端可以生成唯一的订单号，确保订单号的唯一性。（5分）
        String s = "DD" + IdUtil.getSnowflakeNextId();
        house.setOderNo(s);
        //使用Redis实现表单重复提交，代码逻辑正确
        Boolean b = redisTemplate.opsForValue().setIfAbsent("house",house.toString(), 1, TimeUnit.MINUTES);
        if (!b){
            return  BResult.error("不能重复添加");
        }

        boolean save = houseService.save(house);

        return  save?BResult.success():BResult.error();
    }
}
